<style>
.pure_form_extra { width: 800px !important; }
.pure_form_extra .mandatory { color: #ff0000; padding-left: 5px; }
.pure_table_extra { width: 100%; }
.pure_table_extra td { font-family: Lucida Sans Unicode !important; color: #666 !important; }
</style>

<?php 
$PT = PT_DIPLOMA;

$id = Utils::get_param('id', 0);
$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$data = $orm->get('pb_colg_program', NULL, NULL, NULL, NULL, $opts)->d;

$courses = $orm->get('pb_colg_course', 't.code', 'ASC', NULL, NULL, NULL)->d;

$pg = Utils::get_param('pg', 1);
$opts = new stdClass();
$opts->cd = 't.type = :v1';
$opts->cdv = array(':v1' => $PT);
$objs = $orm->get('pb_colg_program', 't.name', 'ASC', $pg, SIZE, $opts);
?>
<div class="pure-form pure-form-aligned pure_form_extra" style="padding: 10px; width: 480px;">
  <legend> Program</legend>
  
  <div class="pure-control-group">
    <label>Type<span class="mandatory">*</span></label>
    <input type="text" class="pure-input-1-2" value="<?php echo $PT; ?>" readonly="true" />
  </div>
  
  <div class="pure-control-group">
    <label>Name<span class="mandatory">*</span></label>
    <input id="name" type="text" class="pure-input-1-2" placeholder="{Name}" />
  </div>
  
  <div class="pure-control-group">
    <label>Formal Name<span class="mandatory">*</span></label>
    <input id="formal_name" type="text" class="pure-input-1-2" placeholder="{Formal Name}" />
  </div>
  
  <div class="pure-control-group">
    <label>Length</label>
    <input id="len" type="text" class="pure-input-1-2" placeholder="{Length}" />
  </div>
  
  <div class="pure-control-group">
    <label>Unit</label>
    <input id="unit" type="text" class="pure-input-1-2" placeholder="{Unit}" />
  </div>
  
  <div class="pure-control-group">
    <label>Comment</label>
    <textarea id="comment" style="resize: none;" class="pure-input-1-2" placeholder="{Comment}"></textarea>
  </div>
  
  <div class="pure-control-group">
    <label>Requirements<button class="pure-button" onclick="add_req();">Add</button></label>
    <div id="reqs" style="text-align: left; padding-left: 135px; margin-top: -40px; min-height: 90px; vertical-align: top;"></div>
  </div>
  
  <div class="pure-control-group">
    <label>&nbsp;</label>
    <button class="pure-button pure-input-1-2 pure-button-primary" onclick="submit_obj();">Save</button>
  </div>
  
  <div class="pure-control-group expg">
    <label>&nbsp;</label>
    <button class="pure-button" onclick="delete_obj();">Delete</button>
    <button class="pure-button" onclick="__data = []; reset(); render();">New Program</button>
  </div>
</div>

<div id="dialog_change" style="display: none; overflow: visible;" title="Or..."></div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __courses = JSON.parse('<?php echo addslashes(json_encode($courses)); ?>');
  var __objs = JSON.parse('<?php echo addslashes(json_encode($objs)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __dir = '<?php echo PLGN_DIR . basename(dirname(__FILE__)); ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __type = '<?php echo $PT; ?>';
  
  $(function() {
    reset();
    render();
  });
  
  function reset() {
    if (__data.length == 0) {
      __data[0] = {
        id: 0,
        name: '',
        len: '',
        unit: '',
        type: __type,
        reqs: '[]',
        comment: ''
      };
    }
    __data[0].reqs = JSON.parse(__data[0].reqs);
  };

  function render() {
    if (__data[0].id != 0) {
      $('.expg').show();
    } else {
      $('.expg').hide();
    }
    Utils.leftbar(
      __objs,
      __data[0].id,
      __type + ' Programs',
      'name',
      function(page) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=' + __file + '&id=' + __data[0].id + '&pg=' + page);
      }
    );
    render_data();
  };
  
  function render_data() {
    Url.insert_param('id', __data[0].id);
    $('#name').val(__data[0].name);
    $('#formal_name').val(__data[0].formal_name);
    $('#len').val(__data[0].len);
    $('#unit').val(__data[0].unit);
    $('#comment').val(__data[0].comment);
    render_reqs();
  };

  function render_reqs() {
    $('#reqs').empty();
    for (var idx in __data[0].reqs) {
      var itm = __data[0].reqs[idx];
      $('#reqs').append('<table id="req_' + idx + '" class="pure-table pure_table_extra">');
      $('#req_' + idx).append('<tr class="pure-table-odd"><td><i onclick="delete_req(' + idx +');"  class="fa fa-times" style="cursor: pointer; float: right;"></i>Select <input onchange="update_num(' + idx +', this.value);" id="req_num_' + idx + '" type="text" value="' + itm.num + '" /></td></tr>');
      $('#req_' + idx).append('<tr class="pure-table-even"><td><select id="req_courses_' + idx + '" multiple="multiple" class="mutilselect"></select></td></tr>');

      for (var idx2 in __courses) {
        var itm2 = __courses[idx2];
        var rslt = Utils.get_by_id(itm2.id, itm.courses);
        if (rslt) {
          $('#req_courses_' + idx).append('<option id="' + idx + '_' + itm2.id + '" value="' + itm2.id +'" selected="selected">' + ((rslt.alias.length == 0) ? itm2.title__ : get_alias(rslt)) + '</option>');
        } else {
          $('#req_courses_' + idx).append('<option id="' + idx + '_' + itm2.id + '" value="' + itm2.id +'">' + itm2.title__ + '</option>');
        }
      }
      $('#reqs').append('</table>');
      $('#reqs').append('<br>')
    }
    $('.mutilselect').touchMultiSelect();
  };

  function get_alias(course) {
    var names = [];
    for (var idx in __courses) {
      var itm = __courses[idx];
      if (itm.id == course.id) {
        names[names.length] = itm.code;
      }
      if ($.inArray(itm.id, course.alias) != -1) {
        names[names.length] = itm.code;
      }
    }
    return names.join(' or ');
  };

  function set_alias(ev, id) {
    var rslt, courses, course_idx, alias;
    rslt = id.split('_');
    courses = __data[0].reqs[rslt[0]].courses;
    for (var idx in courses) {
      var itm = courses[idx];
      if (itm.id == rslt[1]) {
        course_idx = idx;
      }
    }
    alias = __data[0].reqs[rslt[0]].courses[course_idx].alias;
    
    var func = function() {
      __data[0].reqs[rslt[0]].courses[course_idx].alias = $('#name_change').chosen().val() ? $('#name_change').chosen().val() : [];
      $('#dialog_change').dialog('close');
      render_reqs();
    };

    $('#dialog_change').empty();
    $('#dialog_change').append('<select multiple="multiple" id="name_change" style="width: 80%;"></select>');
    $('#dialog_change').dialog({
      position: {
        my: 'left+0 bottom+50',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      },
      width: 500,
      height: 300
    });
    
    $('#name_change').empty();
    for (var idx in __courses) {
      var itm = __courses[idx];
      $('#name_change').append('<option value="' + itm.id + '" ' + (($.inArray(itm.id, alias) == -1) ? '' : 'selected="selected"') + '>' + itm.title__ + '</option>');
    }
    $('#name_change').chosen();
    $("#name_change").trigger("chosen:updated");
  };

  function add_req() {
    __data[0].reqs[__data[0].reqs.length] = {
      num: 1,
      courses: []
    };
    render_reqs();
  };

  function delete_req(idx) {
    __data[0].reqs.splice(idx, 1);
    render_reqs();
  };

  function update_num(idx, val) {
    __data[0].reqs[idx].num = val;
  };

  function add_course(id) {
    var rslt = id.split('_');
    __data[0].reqs[rslt[0]].courses[__data[0].reqs[rslt[0]].courses.length] = {
      id: rslt[1],
      alias: []
    };
  };

  function remove_course(id) {
    var rslt = id.split('_');
    Utils.splice_by_id(rslt[1], __data[0].reqs[rslt[0]].courses);
    var rslt = Utils.get_by_id(rslt[1], __courses);
    $('li[id="' + id + '"]').html(rslt.title__);
    
  };

  function submit_obj() {
    req = __data[0];
    req.name = $('#name').val();
    req.formal_name = $('#formal_name').val();
    req.len = $('#len').val();
    req.unit = $('#unit').val();
    req.comment = $('#comment').val();
    req.reqs = JSON.stringify(req.reqs);
    req.__pg = __objs.p;
    
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        if (rslt.__objs) {
          __objs = rslt.__objs;
          delete rslt.__objs;
        }
        __data[0] = rslt;
        __data[0].reqs = JSON.parse(__data[0].reqs);
        render();
      },
      null
    );
  };
  
  function delete_obj() {
    Ajax.request(
      __requrl.replace(__file, 'index') + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(__data[0])),
      function(rslt) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id);
      },
      { confirm: 1 }
    );
  };

  function get_obj(id) {
    var req = {
      id: id
    };
    Ajax.request(
      __requrl + 'get_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        __data[0].reqs = JSON.parse(__data[0].reqs);
        render();
      },
      null
    );
    return false;
  };
  /*]]>*/
</script>